package com.lee.mysql.config;

import com.lee.mysql.vo.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 由@ControllerAdvice描述的类是 全局异常处理类
 * @RestControllerAdvice等于@ControllerAdvice加上@ResponseBody
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //JDK自带的日志API
    /*
     * @ExceptionHandler(RuntimeException.class)也可以放在Controller里面
     * 但如果每个Controller都写一个ExceptionHandler,代码重复性太多,
     * 所以创建一个@ControllerAdvice全局异常处理类,基于不同的业务,定义不同的
     * 业务异常处理方法
     * 异常处理方法中的参数应与ExceptionHandler(RuntimeException.class)中的
     * 异常类型保持一致
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<String> doHandleRuntimeException(RuntimeException e) {
        //e.printStackTrace();
        log.info("全局报错-{}",e.getMessage(),e);
        return new Result<>(Result.FAIL,e.getMessage());
    }



    /** Shiro登陆认证异常处理 */
    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public Result<String> doHandleRuntimeException(ShiroException e) {
        Result result = new Result();
        result.setErrorCode("1");

        if(e instanceof UnknownAccountException) {
            result.setDesc("账户不存在");
        }else if(e instanceof LockedAccountException) {
            result.setDesc("账户被禁用");
        }else if(e instanceof IncorrectCredentialsException) {
            result.setDesc("密码不正确");
        }else if(e instanceof AuthorizationException) {
            result.setDesc("没有此操作权限");
        }else{
            result.setDesc("系统维护中...");
        }
        //e.printStackTrace();
        log.info("权限报错-{},{}",result.getDesc(),e.getMessage());
        return result;
    }


}
